package com.xhs.config;

import com.xhs.websocket.TestWebSocketHandler;
import com.xhs.websocket.WsHandshakeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

/**
 * @desc: WebSocket 配置（定义连接）
 * @projectName: spring-boot-websocket
 * @author: xhs
 * @date: 2025-03-24 周一 23:16
 * @version: JDK 1.8
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private TestWebSocketHandler testWebSocketHandler;
    @Resource
    private WsHandshakeInterceptor wsHandshakeInterceptor;

    /**
     * 注册 WebSocket 处理器
     *
     * @param registry WebSocket 处理器
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册 WebSocket 处理器到指定的 URL 路径
        registry.addHandler(testWebSocketHandler, "/ws/socket/test")
                // 添加拦截器
                .addInterceptors(wsHandshakeInterceptor)
                // 设置允许的源，允许所有域名访问
                .setAllowedOrigins("*");
    }
}
